package cn.cq.satoken;

import cn.cq.common.BaseConst;
import cn.cq.admin.entity.model.TResource;
import cn.cq.admin.entity.model.TRole;
import cn.cq.admin.service.TResourceService;
import cn.cq.admin.service.TRoleService;
import cn.dev33.satoken.stp.StpInterface;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义权限验证接口扩展
 * 保证此类被SpringBoot扫描，完成Sa-Token的自定义权限验证扩展
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private TResourceService sourceService;
    @Resource
    private TRoleService roleService;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 本list仅做模拟，实际项目中要根据具体业务逻辑来查询权限
        QueryWrapper<TResource> sourceQw = new QueryWrapper<>();
        sourceQw.inSql("id","SELECT trs.resource_id  " +
                "FROM t_user tu,t_role_resource trs,t_role tr  WHERE \n" +
                "tu.role_id = trs.role_id \n" +
                "AND tu.role_id = tr.id \n" +
                //只获取状态为启用的角色对应的资源
                "AND tr.status = 1\n" +
                "AND tu.id = "+ Long.parseLong(loginId.toString()));
        List<TResource> sourceList = sourceService.list(sourceQw);
        List<String> permissionList = sourceList.stream()
                .filter(item ->  item.getStatus() == BaseConst.STATUS_ENABLE
        ).map(item -> item.getSourceKey()).collect(Collectors.toList());
        return permissionList;
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 本list仅做模拟，实际项目中要根据具体业务逻辑来查询角色
        QueryWrapper<TRole> roleQw = new QueryWrapper<>();
        roleQw.inSql("id","SELECT tu.role_id  " +
                "FROM t_user tu WHERE \n" +
                "tu.id = "+ Long.parseLong(loginId.toString()));
        List<TRole> list = roleService.list(roleQw);
        List<String> roleList = list.stream()
                .filter(item ->  item.getStatus() == BaseConst.STATUS_ENABLE
        ).map(item -> item.getValue()).collect(Collectors.toList());
        return roleList;
    }

}
